package com.mrdeer.iot.service.impl;

import com.mrdeer.common.tools.ConvertCode;
import com.mrdeer.iot.NettyServer;
import com.mrdeer.iot.service.DriverCustomService;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Slf4j
@Service
public class DriverCustomServiceImpl implements DriverCustomService {

    @Resource
    private NettyServer nettyServer;

    @Resource
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Override
    public void initial() {
        threadPoolTaskExecutor.execute(() -> {
            log.info("Netty Driver Starting incoming data listener");
            nettyServer.start();
        });
    }

//    @Override
//    public String read(Device device, Point point) {
//        return "nil";
//    }

//    @Override
//    public Boolean write(Device device, AttributeInfo value) {
//        //TODO:获取设备的Channel，并向下发送数据
//        Channel channel = NettyServer.deviceChannelMap.get(device.getName());
//        if (null != channel) {
//            //netty需要用ByteBuf传输
//            ByteBuf buff = Unpooled.buffer();
//            //对接需要16进制
//            buff.writeBytes(ConvertCode.hexString2Bytes(value.getValue()));
//            channel.writeAndFlush(buff);
//        }
//        return true;
//    }

    @Override
    public Boolean write(String dest, String value) {
        log.info("dest--------------->" + dest);
        log.info("value--------------->" + value);
        Channel channel = NettyServer.deviceChannelMap.get(dest);
        if (null != channel) {
            //netty需要用ByteBuf传输
            ByteBuf buff = Unpooled.buffer();
            //对接需要16进制
            buff.writeBytes(ConvertCode.hexString2Bytes(value));
            channel.writeAndFlush(buff);
        }
        return true;
    }

    @Override
    public void schedule() {
        /**
         * 上传设备状态
         * DeviceStatus:
         * ONLINE:在线
         * OFFLINE:离线
         * MAINTAIN:维护
         * FAULT:故障
         */
//        log.info("deviceMap size :" + driverContext.getDriverMetadata().getDeviceMap().size());
//        driverContext.getDriverMetadata().getDeviceMap().keySet().forEach(
//                id -> nettyDriverService.deviceEventSender(id, MRDeerCommon.Device.Event.HEARTBEAT, MRDeerCommon.Device.Status.ONLINE)
//        );
    }
}
